package com.cssl.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.cssl.domain.dto.AddComment;
import com.cssl.domain.dto.DtsCommentDto;
import com.cssl.domain.vo.DtsCommentVO;
import com.cssl.mapper.DtsCommentMapper;
import com.cssl.mapper.DtsUserMapper;
import com.cssl.service.DtsCommentService;
import com.cssl.util.*;
import com.fasterxml.jackson.core.type.TypeReference;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class DtsCommentServiceImpl implements DtsCommentService {
    @Autowired
    private DtsCommentMapper dtsCommentMapper;
    @Autowired
    private ObjectMapperUtil objectMapperUtil;
    @Autowired
    private StringRedisTemplate template;
    @Autowired
    private DtsUserMapper userMapper;
    @Autowired
    private FileUpload fileUpload;

    @Override
    public Result getUserComment(DtsCommentDto comment) {
        System.out.println("comment = " + comment);
        List<Integer> commentList = null;
        List<Map> userMap = null;
        Map map = new HashMap<>();

        // 先从redis中获取
        String s = template.opsForValue().get(StorageVariable.USERCOMMENTGOODS + ":" + comment.getValueId());
        String s1 = template.opsForValue().get(StorageVariable.USERCOMMENTGOODSCONTENT + ":" + comment.getValueId());
        if (StrUtil.isEmpty(s) || StrUtil.isEmpty(s1)) {
            commentList = dtsCommentMapper.getUserComment(comment).stream().distinct().collect(Collectors.toList());
            template.opsForValue().set(StorageVariable.USERCOMMENTGOODS + ":" + comment.getValueId(), objectMapperUtil.toJsonString(commentList), 7, TimeUnit.DAYS);
            // 根据用户id查询用户具体信息
            Page page = PageHelper.startPage(comment.getPage(), comment.getSize());
            Map searchMap = new HashMap();
            searchMap.put("idList", commentList);
            searchMap.put("type", comment.getType());
            searchMap.put("valueId", comment.getValueId());
            userMap = userMapper.getUserCommentById(searchMap); // 存进redis中
// 日期时间格式化器
            DateTimeFormatter inputFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
            DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            List<Map<String, Object>> collect = userMap.stream().map(c -> {
                String addTime = c.get("addTime").toString();
                LocalDateTime dateTime = LocalDateTime.parse(addTime, inputFormatter);
                Map<String, Object> updatedMap = new HashMap<>(c);
                String formattedDate = dateTime.format(outputFormatter);
                updatedMap.put("addTime", formattedDate);
                return updatedMap;
            }).collect(Collectors.toList());
            template.opsForValue().set(StorageVariable.USERCOMMENTGOODSCONTENT + ":" + comment.getValueId() + ":" + comment.getPage(), objectMapperUtil.toJsonString(page.getResult()), 7, TimeUnit.DAYS);
            // 存储进redis(7天过期)
            map.put("commentList", collect);
            if (ObjectUtil.isEmpty(collect)) {
                map.put("commentCount", 0);
                return Result.result(InfoCode.OK, InfoCode.MESSAGE_OK, map, System.currentTimeMillis());
            }
            if (comment.getShowType() == 0) {
                map.put("commentCount", collect.size());
            } else {
                map.put("commentCount", page.getTotal());
            }
            return Result.result(InfoCode.OK, InfoCode.MESSAGE_OK, map, System.currentTimeMillis());

        }
        // 都不为空
        List<Map> mapList = objectMapperUtil.fromJsonString(s1, new TypeReference<List<Map>>() {
        });
        map.put("commentList", mapList);
        if (comment.getShowType() == 0) {
            map.put("commentCount", mapList.size());
        } else {
            // 使用 keys 方法获取所有以给定前缀开头的键
            Set<String> keys = template.keys(StorageVariable.USERCOMMENTGOODSCONTENT + "*");
            objectMapperUtil.fromJsonString(template.opsForValue().get(keys + ":" + comment.getValueId()), new TypeReference<List<Map>>() {
            }).stream().forEach(c -> mapList.add(c));
            map.put("commentCount", mapList.size());
        }
        return Result.result(InfoCode.OK, InfoCode.MESSAGE_OK, map, System.currentTimeMillis());
    }

    @Override
    public Result addComment(AddComment comment) {
        int loginIdAsInt = StpKit.USER.getLoginIdAsInt();
        List<String> uploadUrl = new ArrayList<>();
        List<String> picUrls = comment.getPicUrls();
        List<byte[]> binaryData = comment.getBinaryData();
        int i = 0;
        if (ObjectUtil.isEmpty(picUrls)) {
            comment.setHasPicture(0);
        } else {
            comment.setHasPicture(1);
        }
        for (String name : picUrls) {
            String[] s = name.split("\\.");
            String newName = UUID.randomUUID() + "." + s[1];
            String upload = fileUpload.upload(binaryData.get(i), newName);
            System.out.println("upload = " + upload);
            uploadUrl.add(upload);
            i++;
        }

        String urls = objectMapperUtil.toJsonString(uploadUrl);
        System.out.println("urls = " + urls);
        Integer res = dtsCommentMapper.addComment(loginIdAsInt, comment, urls);
        if (res > 0) {
            // 新增成功,修改redis存储的数据
            Set<String> keys = template.keys(StorageVariable.USERCOMMENTGOODSCONTENT + "*");
            Set<String> keys1 = template.keys(StorageVariable.USERCOMMENTGOODS + "*");
            Long delete = template.delete(keys);
            Long delete2 = template.delete(keys1);
            if (delete > 0 || delete2 > 0) {
                // 成功
                return Result.result(InfoCode.OK, InfoCode.MESSAGE_OK, res, System.currentTimeMillis());
            }
        }
        return Result.fail(InfoCode.FAILED, InfoCode.MESSAGE_FAILED, System.currentTimeMillis());
    }

    @Override
    public Map getCommentVOGoodsList(DtsCommentVO commentVO) {
        Page page = PageHelper.startPage(commentVO.getPageNum(), commentVO.getPageSize());
        dtsCommentMapper.getCommentVOGoodsList(commentVO);
        Map map = new HashMap<>();
        map.put("list", page.getResult());
        map.put("total", page.getTotal());
        map.put("totalPage", page.getPages());
        map.put("pageNum", page.getPageNum());
        map.put("pageSize", page.getPageSize());
        return map;
    }

    @Override
    public Integer deleteComment(Integer id) {
        return dtsCommentMapper.deleteComment(id);
    }
}
